#include "accessKeyRes.h"
#include "jsonUtils.h"
#include "stringUtils.h"

JsonDoc& AccessKeyRes::jsonDeserialize(const String& json)
{
	JsonDoc& doc = OperatorResponse::jsonDeserialize(json);
	const JsonValue::ConstMemberIterator& it = doc.FindMember(L"data");
	if (it != doc.MemberEnd() && it->value.IsObject()) {
		accessKey.jsonDeserialize(it->value);
	}
	return doc;
}

const AccessKey& AccessKeyRes::getAccessKey() const
{
	return accessKey;
}

AccessKey::AccessKey()
{

}

AccessKey::~AccessKey()
{
}

void AccessKey::jsonDeserialize(JsonValue const& v)
{
	String access, secret, securityToken, expiresAt, region, bucket, serverType;
	JsonUtils::loadStr(v, L"access", access);
	JsonUtils::loadStr(v, L"secret", secret);
	JsonUtils::loadStr(v, L"expiresAt", expiresAt);
	JsonUtils::loadStr(v, L"securityToken", securityToken);
	JsonUtils::loadStr(v, L"region", region);
	JsonUtils::loadStr(v, L"bucket", bucket);
	JsonUtils::loadStr(v, L"serverType", serverType);
	long expiresIn = 0;
	if (!expiresAt.empty()) {
		int y, m, d, H, M, s;
		swscanf_s(expiresAt.c_str(), L"%d-%02d-%02d %02d:%02d:%02d", &y, &m, &d, &H, &M, &s);
		tm tm;
		tm.tm_year = y - 1900;
		tm.tm_mon = m - 1;
		tm.tm_mday = d;
		tm.tm_hour = H;
		tm.tm_min = M;
		tm.tm_sec = s;
		time_t server = mktime(&tm);

		time_t t = 0;
		time_t t2 = time(&t);

		expiresIn = server - t;
	}
	endClock = clock() + expiresIn * CLOCKS_PER_SEC;
	this->access = StringUtils::Wstring2string(access.c_str());
	this->secret = StringUtils::Wstring2string(secret.c_str());
	this->securityToken = StringUtils::Wstring2string(securityToken.c_str());
	this->region = StringUtils::Wstring2string(region.c_str());
	this->bucket = StringUtils::Wstring2string(bucket.c_str());
	this->serverType = StringUtils::Wstring2string(serverType.c_str());
}

const std::string& AccessKey::getAccess() const
{
	return access;
}

const std::string& AccessKey::getSecret() const
{
	return secret;
}

const std::string& AccessKey::getSecurityToken() const
{
	return securityToken;
}

const std::string& AccessKey::getRegion() const
{
	return region;
}

const std::string& AccessKey::getBucket() const
{
	return bucket;
}

bool AccessKey::nearestExpire() const
{
	return clock() + 10 * 60 * CLOCKS_PER_SEC >= endClock;
}

long AccessKey::timeRemain() const
{
	return (endClock - clock())/ CLOCKS_PER_SEC;
}

bool AccessKey::isTencentServer() const
{
	if (serverType.empty()) 
	{
		return false;
	}
	if (serverType == "tencent") {
		return true;
	}
	return false;
}
